<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input
              placeholder="请输入用户名"
              v-model="queryinfo.username"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select
              placeholder="请选择用户状态"
              v-model="queryinfo.status"
              clearable
          >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="getUserList"
          >搜索</el-button
          >
        </el-col>
        <el-col :span="1">
          <el-button type="danger" icon="el-icon-delete" @click="btndelete">删除</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表(表格)区域 -->
      <el-table
          ref="multipleTable"
          border
          stripe
          :data="userList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          empty-text="没有数据"
      >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column label="登录名" prop="loginname"></el-table-column>
        <el-table-column label="密码" prop="password"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="状态" prop="status"></el-table-column>
        <el-table-column label="创建时间" prop="createdate"></el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUserById(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <!--            <el-button-->
            <!--              type="danger"-->
            <!--              icon="el-icon-delete"-->
            <!--              size="mini"-->
            <!--              @click="removeUserById(scope.row.id)"-->
            <!--            ></el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryinfo.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList();
  },
  data() {
    return {
      userList: [],
      queryinfo: {
        username: "",
        status: "",
        pageNum: 1,
        pageSize: 5,
      },
      // 初始化 multipleSelection
      multipleSelection: [],
      total: 0,
      options: [
        {
          value: "1",
          label: "普通用户",
        },
        {
          value: "2",
          label: "管理员",
        },
        {
          value: "3",
          label: "超级管理员",
        },
      ],
    };
  },
  methods: {
    //删除公告
    getUserIds(){
      return this.multipleSelection.map(item => item.id)
    },
    btndelete(){

      // 判断是否有选中用户
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择删除的用户'
        });
        return;
      }

      this.$confirm('此操作将永久删除这些用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const list=this.getUserIds()
        // console.log(`打印当前list：${list}`)
        this.$http.delete("/users/delete",{
          data: list,
          headers: {
            'Content-Type': 'application/json'
          }
        }).then( async resp =>{
          // console.log(resp)
          if(resp.data.flag){
            this.$message({
              type: 'success',
              message: '删除成功!',


            });
            //循环过滤掉userList里面被多选删除的id
            // let i=0;
            for (let item of list) {
              this.userList = this.userList.filter((v) => v.id !== item);
              console.log("当前用户列表:", this.userList);
            }


            // 这里可以增加调试信息，查看更新后的用户列表

            // 检查当前页是否还有数据，如果没有并且当前页数大于1，则页码减一再获取数据
            if (this.userList.length === 0 && this.queryinfo.pageNum > 1) {
              this.queryinfo.pageNum--; // 页码减一
              console.log(this.queryinfo.pageNum + "页码减一");
              await this.getUserList(); // 重新获取上一页的数据
            } else {
              await this.getUserList(); // 重新获取当前页的数据
            }
            // this.queryparams.currentPage=1
            this.getUserList()
          }

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async getUserList() {
      try {
        const { data: res } = await this.$http.post(
            "users/list",
            this.queryinfo
        );
        // console.log(res);

        if (res.flag) {
          // 赋值总数
          this.total = res.data.total;

          // 处理用户数据
          this.userList = res.data.rows.length ? res.data.rows.map((v) => {
            v.createdate = this.$moment(v.createdate).format(
                "YYYY-DD-MM HH:mm:ss"
            );
            v.password = "*****"; // 隐藏密码处理
            if (v.status === 1) {
              v.status = "普通用户";
            } else if (v.status === 2) {
              v.status = "管理员";
            } else if (v.status === 3) {
              v.status = "超级管理员";
            }
            return v; // 返回处理后的用户对象
          }) : [];
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    },

    btnsearch() {
      this.$http.get("getuser", {
        params: {
          uname: this.queryinfo.uname,
          status: this.queryinfo.status,
        },
      });
      this.getUserList();
    },
    handleSizeChange(v) {
      this.queryinfo.pageSize = v;
      this.getUserList();
    },
    handleCurrentChange(v) {
      this.queryinfo.pageNum = v;
      this.getUserList();
    },
    // async removeUserById(id) {
    //   const confirmResult = await this.$confirm("请问是否要永久删除该用户", {
    //     confirmButtonText: "确认删除",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).catch((err) => err);
    //
    //   // 如果用户点击确认，则confirmResult 为'confirm'
    //   // 如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
    //   if (confirmResult !== "confirm") {
    //     return this.$message.info("已经取消删除");
    //   }
    //
    //   const { data: res } = await this.$http.delete("/users/delete/" + id);
    //
    //   if (res.code !== 200) return this.$message.error(res.message);
    //   // 修改成功的提示
    //   this.$message.success(res.message);
    //   //移除当前信息
    //   this.userList = this.userList.filter((v) => v.id !== id);
    //   // 这里可以增加调试信息，查看更新后的用户列表
    //   console.log("当前用户列表:", this.userList);
    //   // 检查当前页是否还有数据，如果没有并且当前页数大于1，则页码减一再获取数据
    //   if (this.userList.length === 0 && this.queryinfo.pageNum > 1) {
    //     this.queryinfo.pageNum--; // 页码减一
    //     console.log(this.queryinfo.pageNum + "页码减一");
    //     await this.getUserList(); // 重新获取上一页的数据
    //   } else {
    //     await this.getUserList(); // 重新获取当前页的数据
    //   }
    // },
    editUserById(row) {
      delete row.faceurl;
      delete row.password;
      this.$router.push({ path: "/useredit", query: row });
    },

  },
};
</script>

<style></style>
